import HTMLParser from "@/uni_modules/html-parser/js_sdk/index.js"
import request from '@/uni_modules/yingbing-request/js_sdk'
import Config from '@/assets/js/config.js'

const { ERR_OK, ERR_FALSE, hotspot } = Config

const requestFunction = {
	baidu: function (res) {
		let document = new HTMLParser(res.data.trim())
		let hotsearch_data = document.getElementById('hotsearch_data')
		let data = JSON.parse(hotsearch_data.innerHTML.trim())
		return data.hotsearch.map(hot => {
			return {
				title: hot.card_title,
				linkurl: hot.linkurl,
				score: hot.heat_score
			}
		})
	},
	tencent: function (res) {
		return res.data.idlist[0].newslist.filter(hot => hot.url).map(hot => {
			return {
				title: hot.title,
				linkurl: hot.url,
				score: hot.readCount
			}
		})
	}
}

export default async function (arr) {
	const list = []
	const https = arr.map(id => {
		const index = hotspot.findIndex(hot => hot.id == id)
		if ( index > -1 ) {
			return new Promise((resolve, reject) => {
				request.http.get(hotspot[index].href, hotspot[index].options).then(res => {
					try{
						resolve({
							code: ERR_OK,
							data: {
								list: requestFunction[id](res)
							}
						})
					}catch(e){
						resolve({
							code: ERR_FALSE,
							data: {
								list: []
							}
						})
					}
				}).catch(err => {
					reject(err)
				})
			})
		} else {
			return new Promise(resolve => [
				resolve({
					code: ERR_FALSE,
					data: {
						list: []
					}
				})
			])
		}
	})
	return await Promise.all(https).then(ress => {
		ress.forEach((res,key) => {
			if ( res.code == ERR_OK ) {
				const index = hotspot.findIndex(hot => hot.id == arr[key])
				if ( index > -1 ) {
					list.push({
						id: hotspot[index].id,
						title: hotspot[index].title,
						logo: hotspot[index].logo,
						list: res.data.list
					})
				}
			}
		})
		return list
	})
}